package com.zyh.controller;

import com.zyh.entity.*;
import com.zyh.service.OrderItemService;
import com.zyh.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ModelAndView mav;

    @RequestMapping("/insertOrder")
    public ModelAndView insertOrder(Integer addressId, HttpSession session){
        //订单表添加
        /*
        * orderId 不需要 自动增加
        * goodPrice 需要 session.cart.buyMap
        * orderTime 不需要 now()
        * orderState 不需要 默认1
        * address_id 需要 前端传
        * user_id 需要 session.user.id
        * */
        Order order = new Order();
        User user =(User) session.getAttribute("user");
        Cart cart = (Cart) session.getAttribute("cart");
        order.setUser(user);

        Address address = new Address();
        address.setAid(addressId);
        order.setAddress(address);

        order.setOrderState(1);//默认1

        order.setGoodPrice(cart.getTotalMoney());

        orderService.insertOrder(order);

        //订单详情表添加
        //循环buyMap
        /*
        * id 不需要 自增
        * product_id 需要
        * order_id
        * count
        * amount
        * */
        Map<Integer, CartItem> buyMap = cart.getBuyMap();
        Set<Map.Entry<Integer, CartItem>> entries = buyMap.entrySet();
        for(Map.Entry<Integer,CartItem> entry : entries){
            OrderItem orderItem = new OrderItem();

            CartItem value = entry.getValue();
            Book book = value.getBook();
            orderItem.setBook(book);

            orderItem.setOrder(order);

            orderItem.setCount(value.getCount());

            orderItem.setAmount(value.getCount()*value.getBook().getDangPrice());
            orderItemService.insertOrderItem(orderItem);
        }

        mav.setViewName("redirect:/order/order_ok.jsp");
        return mav;
    }

    @RequestMapping("/selectByUserId")
    public ModelAndView selectByUserId(HttpSession session){
        User user =(User) session.getAttribute("user");
        if(user!=null){
            List<Order> orders = orderService.selectByUserId(user.getId());
            mav.addObject("orders",orders);
            mav.setViewName("/order/my_order.jsp");
        }else{
            mav.setViewName("redirect:/user/login_form.jsp");
        }
        return mav;
    }
}
